package cn.net.isir.tasker;

import cn.net.isir.core.SpringApplicationContextUtils;
import cn.net.isir.entity.*;
import cn.net.isir.service.*;
import cn.net.isir.service2.ShopService;
import cn.net.isir.service2.ShopUserService;
import cn.net.isir.service2.TurnService2;
import cn.net.isir.utils.NumberUtils;
import org.apache.log4j.Logger;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author liuxubo
 * @filename ShopTurnTask.java
 * @package cn.net.isir.tasker
 * @email lxb@isir.net.cn
 * @date 2019/03/29
 * @comment
 * @since 1.8
 */
public class ShopTurnTask {
    //声明日志对象
    private static Logger logger = Logger.getLogger(ShopTurnTask.class);
    //计时器
    private static Timer timer = new Timer();
    //任务对象
    private static TimerTask timerTask;

    /**
     * 店铺转出业务类
     */
    private static TurnShopService turnShopService = (TurnShopService) SpringApplicationContextUtils.getBean("turnShopService");

    /**
     * 转出业务类
     */
    private static TurnService turnService = (TurnService) SpringApplicationContextUtils.getBean("turnService");

    /**
     * 转出业务类
     */
    private static TurnService2 turnService2 = (TurnService2) SpringApplicationContextUtils.getBean("turnService2");

    /**
     * 转出批次
     */
    private static TurnBarcodeService turnBarcodeService = (TurnBarcodeService) SpringApplicationContextUtils.getBean("turnBarcodeService");

    /**
     * 用户组织机构表
     */
    private static UserOrgService userOrgService = (UserOrgService) SpringApplicationContextUtils.getBean("userOrgService");

    /**
     * 用户表
     */
    private static UserService userService = (UserService) SpringApplicationContextUtils.getBean("userService");

    /**
     * 用户店铺关联表
     */
    private static ShopUserService shopUserService = (ShopUserService) SpringApplicationContextUtils.getBean("shopUserService");
    /**
     * 店铺表
     */
    private static ShopService shopService = (ShopService) SpringApplicationContextUtils.getBean("shopService");

    /**
     * crm用户管理
     */
    private static CRMUserManagerService crmUserManagerService = (CRMUserManagerService) SpringApplicationContextUtils.getBean("CRMUserManagerService");

    /**
     * 系数
     */
    private static FactorService factorService = (FactorService) SpringApplicationContextUtils.getBean("factorService");

    /**
     * 奖牌
     */
    private static MedalsService medalsService = (MedalsService) SpringApplicationContextUtils.getBean("medalsService");


    /**
     * 初始化方法
     */
    private static void init() {
        logger.info("AlipaySignHandleTask.init();");
        if (timerTask == null) {
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    //查询系数
                    Factor factor = factorService.selectOne(null);
                    List<Medals> medalsList = medalsService.selectList(null);
                    // 查询转结表，查看是否有上个月的转出数据
                    Calendar calendar = Calendar.getInstance();
                    int monthInt = calendar.get(Calendar.MONTH);
                    monthInt++;
                    // 批次编号
                    String month = monthInt < 10 ? "0" + monthInt : String.valueOf(monthInt);
                    String year = String.valueOf(calendar.get(Calendar.YEAR));
                    String barcodeNo = year + month;
                    TurnBarcode turnBarcode = new TurnBarcode();
                    turnBarcode.setCnNumber(barcodeNo);
                    turnBarcode = turnBarcodeService.selectOne(turnBarcode);
                    // 1.如果已经有数据，则不做处理
                    if (turnBarcode != null) {
                        return;
                    }
                    turnBarcode = new TurnBarcode();
                    turnBarcode.setCnNumber(barcodeNo);
                    turnBarcode.setBarcodeStatus("processing");
                    turnBarcode.setHandleStartTime(new Date());
                    turnBarcodeService.insert(turnBarcode);
                    // 2.如果没有数据，进行转出
                    // 人员列表
                    List<User> userList = userService.selectList(null);
                    // 每个人员的未转出店铺列表
                    for (User user1 : userList) {

                        Date turnDate = new Date();

//                        ShopUser shopUser = new ShopUser();
//                        shopUser.setUserId(user1.getId());
//                        List<ShopUser> shopUserList = shopUserService.selectList(shopUser);
                        Shop shop = new Shop();
                        shop.setSalesmanCode(user1.getId());
                        List<Shop> shopList = shopService.selectList(shop);


                        ArrayList<Shop> noTurnedShopList = new ArrayList<>();
                        for (Shop shop1 : shopList) {
                            boolean isTurned = false;
                            String ids = crmUserManagerService.getTurnedShopIds();
                            if (ids != null && ids.length() > 0) {
                                String[] idArray = ids.split(",");
                                for (String s : idArray) {
                                    if (s.equals(shop1.getId())) {
                                        isTurned = true;
                                    }
                                }
                            }
                            if (!isTurned) {
                                noTurnedShopList.add(shop1);
                            }
                        }
                        int monthOrderDays;

                        BigDecimal monthShopTotalTurnFlow = BigDecimal.ZERO;


                        Turn turn = new Turn();
                        turn.setTurnBarcodeId(turnBarcode.getId());
                        turn.setShopIds(null);
                        turn.setShopName(null);
                        turn.setTurnTime(turnDate);
                        turn.setUserId(user1.getId());
                        UserOrg userOrg = userOrgService.selectByUserId(user1.getId());
                        turn.setOrgId(userOrg == null ? null : userOrg.getOrgId());
                        turn.setIsExported(0);
                        turn.setTurnAmount(BigDecimal.ZERO);// 需要更新
                        turn.setMonthAmount(BigDecimal.ZERO);// 需要更新
                        turn.setTurnPercent(factor.getRollOut());
                        turn.setMonthPercent(factor.getRollBefore());
                        turn.setMedalFactor(null);
                        turn.setTurnFee(null);// 需要更新
                        turn.setMonthFee(null);// 需要更新
                        turnService.insert(turn);

                        BigDecimal shopTurnAmount = BigDecimal.ZERO;
                        BigDecimal shopFlowAmount = BigDecimal.ZERO;
                        BigDecimal shopTurnFee = BigDecimal.ZERO;
                        BigDecimal shopFlowFee = BigDecimal.ZERO;

                        // 找到每个人员符合转出条件的店铺列表
                        List<Shop> canTurnedList = new ArrayList<>();
                        for (Shop shop1 : noTurnedShopList) {
                            List<TimeRange> timeRangeList = crmUserManagerService.getTimeRangeList(shop1.getSalesmanCode());

                            BigDecimal turnFlow = BigDecimal.ZERO;
                            BigDecimal monthTurnTemp = BigDecimal.ZERO;
                            BigDecimal monthTotalTemp = BigDecimal.ZERO;

                            List<Map<String, Object>> infoList = turnService2.getLastMonthShopTurnInfoByShopId(factor.getPreset2(), shop1.getId(), timeRangeList);
                            monthOrderDays = 0;
                            for (Map<String, Object> map : infoList) {
                                // 日订单数大于20,则加入统计
                                if (BigDecimal.valueOf(Double.parseDouble(String.valueOf(map.get("dayOrderCount")))).compareTo(factor.getPreset1()) > 0) {
                                    monthOrderDays++;
                                    monthTurnTemp = monthTurnTemp.add(BigDecimal.valueOf(Double.parseDouble(String.valueOf(map.get("finalTotal")))));
                                    if (NumberUtils.toBigDecimal(monthOrderDays).compareTo(factor.getPreset3()) > 0) {
                                        break;
                                    }
                                }
                                //所有流水
                                List<Order> orderList = turnService2.getLastMonthTotalFlowByShopId(shop1.getId(), timeRangeList);
                                for (Order order : orderList) {
                                    monthTotalTemp = monthTotalTemp.add(order.getFinalTotal());
                                }
                            }
                            if (NumberUtils.toBigDecimal(monthOrderDays).compareTo(factor.getPreset3()) > 0) {
                                canTurnedList.add(shop1);
                                turnFlow = monthTurnTemp;
                            }
                            monthShopTotalTurnFlow = monthShopTotalTurnFlow.add(turnFlow);
                            TurnShop turnShop = new TurnShop();
                            turnShop.setTurnId(turn.getId());
                            turnShop.setShopId(shop1.getId());
                            turnShop.setTurnAmount(turnFlow);
                            turnShop.setMonthAmount(monthTotalTemp);
                            BigDecimal tempMedalFactor = BigDecimal.ZERO;
                            // 获取奖牌系数
                            for (Medals medals : medalsList) {
                                if (monthTotalTemp.compareTo(medals.getMin()) >= 0 && monthTotalTemp.compareTo(medals.getMax()) < 0) {
                                    tempMedalFactor = medals.getFactor();
                                }
                            }
                            turnShop.setMedalFactor(tempMedalFactor);
                            turnShop.setTurnFee(turnFlow.multiply(factor.getRollOut()).multiply(tempMedalFactor));
                            turnShop.setMonthFee(monthTotalTemp.multiply(factor.getRollBefore()));
                            // 如果有转出佣金，则插入数据，否则不插入数据
                            if (turnShop.getTurnAmount().compareTo(BigDecimal.ZERO) > 0) {
                                turnShopService.insert(turnShop);
                            }
                            // 统计所有
                            shopTurnAmount = shopTurnAmount.add(turnShop.getTurnAmount());
                            shopFlowAmount = shopFlowAmount.add(turnShop.getMonthAmount());
                            shopTurnFee = shopTurnFee.add(turnShop.getTurnFee());
                            shopFlowFee = shopFlowFee.add(turnShop.getMonthFee());
                        }
                        // 更新转出记录
                        turn.setTurnAmount(shopTurnAmount);
                        turn.setMonthAmount(shopFlowAmount);
                        turn.setTurnFee(shopTurnFee);
                        turn.setMonthFee(shopFlowFee);
                        // 如果有店铺转出，则更新转出金额等
                        if (turn.getTurnAmount().compareTo(BigDecimal.ZERO) > 0) {
                            turnService.update(turn);
                        } else {//没有转出记录则删掉t_turn表中的转出记录
                            turnService.delete(turn.getId());
                        }
                    }
                    // 更新批次状态
                    turnBarcode.setBarcodeStatus("Processed");
                    turnBarcode.setHandleEndTime(new Date());
                    turnBarcodeService.update(turnBarcode);
                }
            };
        }
    }

    /**
     * 执行任务
     */
    public static void run() {
        logger.info("ShopTurnTask.run();");
        init();
        //1分钟之后执行第一次，以后每5分钟执行一次
        timer.schedule(timerTask, 60 * 1000, 5 * 60 * 1000);
    }

    /**
     * 取消任务
     */
    public static void cancel() {
        logger.info("ShopTurnTask.cancel();");
        timer.cancel();
    }

}
